import dashscope
from dashscope import Generation
from flask import Flask, request, jsonify
from flask_cors import CORS
import time

dashscope.api_key = "sk-ee9cb3489bda4d4fbb3ea7393d809d95"


# 封装大模型接口
def ask_qwen(prompt: str, temperature=0.7):
    response = Generation.call(
        model="qwen-turbo",
        prompt=prompt,
        temperature=temperature
    )
    if response.status_code == 200:
        return response.output.text
    else:
        return f"错误：{response.message}"


# 创建Flask应用
app = Flask(__name__)
CORS(app)  # 允许跨域请求


# 对话接口
@app.route('/api/chat', methods=['POST'])
def chat():
    """处理对话请求"""
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            return jsonify({
                "success": False,
                "message": "请求数据不能为空"
            }), 400

        user_input = data.get('message', '').strip()

        # 验证输入
        if not user_input:
            return jsonify({
                "success": False,
                "message": "消息内容不能为空"
            }), 400

        # 调用大模型
        start_time = time.time()
        response = ask_qwen(user_input)
        response_time = round(time.time() - start_time, 2)

        # 返回响应
        return jsonify({
            "success": True,
            "data": {
                "response": response,
                "response_time": response_time,
                "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
            }
        })

    except Exception as e:
        return jsonify({
            "success": False,
            "message": f"服务器错误: {str(e)}"
        }), 500


# 健康检查接口
@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        "success": True,
        "message": "服务运行正常"
    })


if __name__ == "__main__":
    print("🚀 启动聊天API服务...")
    print("📚 可用接口:")
    print("   POST http://localhost:5000/api/chat - 对话接口")
    print("   GET  http://localhost:5000/api/health - 健康检查")
    print("\n🎯 服务已启动: http://localhost:5000")

    app.run(host='0.0.0.0', port=5000, debug=True)